package ru.passivemoney.common;

import java.text.SimpleDateFormat;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.JFAuthenticationException;
import com.dukascopy.api.system.JFVersionException;

public class Utils {
	private static final Logger logger = LoggerFactory.getLogger(Utils.class);
	private static int CONNECT_COUNT = 1;
	
	public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss_SSS");
	
	/**
     * Подключает клиента один раз
     * @param client
     * @param credentials
     */
    public static void connectClient(IClient client, Credentials credentials) throws JFAuthenticationException, JFVersionException, Exception{
    	logger.info("{} attempt to connect.", CONNECT_COUNT++);
        client.connect(Consts.jnlpUrl, credentials.getUserName(), credentials.getPassword());
    }
    
    /**
     * Подключает клиента до тех пор, пока не подключит. Интервал между попытками - 10 секунд
     * @param client
     * @param credentials
     * @throws InterruptedException 
     */
    public static void connectClientInfinity(IClient client, Credentials credentials) {
    	boolean connected = false;
    	
    	while(!connected){
    		try{
    			connectClient(client, credentials);
    			for(int i = 0; (i < 20) && !client.isConnected(); i++){
    				try {
						Thread.sleep(5000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
    			}
    		}catch(Exception e){
    			logger.error("Error when connecting", e);
    			for(int i = 0; (i < 10) && !client.isConnected(); i++){
    				try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
    			}
    		}finally{
    			if (client.isConnected()) {
    	            connected = true;
    	        }
    		}
    	}
    	
    }
    
    public static <T> String setToString(Set<T> set){
    	if(set == null || set.size() < 1) return "";
    	
    	StringBuilder out = new StringBuilder();
    	for(T element : set){
    		out.append(element).append(", ");
    	}
		return out.substring(0, out.length() - 2);
    	
    }

}
